package com.kgis.fm.business.drawfeature {
	import com.kgis.flexutil.StringUtils;
	import com.kgis.fm.business.component.AttributeDialogTab;
	import com.kgis.fm.business.component.EntityDialog;
	import com.kgis.fm.business.event.RequestFormEvent;
	import com.kgis.fm.common.event.AddGeometryEvent;
	import com.kgis.fm.common.event.CommonEntityEvent;
	import com.kgis.fm.common.manager.MetaDataManager;
	import com.kgis.fm.flex.model.business.Entity;
	import com.kgis.fm.flex.model.business.ExtensionAttributes;
	import com.kgis.fm.flex.model.business.GeometryEntity;
	import com.kgis.fm.flex.model.metadata.Connectionship;
	import com.kgis.fm.flex.model.metadata.Ownership;
	import com.kgis.fm.flex.model.term.LegendEntry;
	import com.kgis.map.common.util.ResourceUtil;
	import com.kgis.map.constant.StringConstants;
	import com.kgis.map.events.DrawEvent;
	import com.kgis.map.events.EditEvent;
	import com.kgis.map.feature.Feature;
	import com.kgis.map.geometry.AbstractGeometry;
	import com.kgis.map.geometry.PointGeometry;
	import com.kgis.map.geometry.basetype.Location;
	import com.kgis.map.handler.feature.draw.EditHandler;
	import com.kgis.map.style.PointStyle;
	import com.kgis.mvc.CommandCompletionEvent;
	import com.kgis.mvc.ViewRegistry;
	import com.kgis.widgets.controls.Dialog;
	import com.kgis.widgets.managers.ConfirmHelper;
	import com.kgis.widgets.managers.ErrorManager;
	
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.ui.Keyboard;
	
	import fm.kgis.fm.service.FmEntityManagementService;
	import fm.kgis.fm.service.ServiceManager;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.events.CloseEvent;
	import mx.managers.PopUpManager;

    /**
     * @author Simon He
     * */
    [Event(name="{com.kgis.fm.business.event.RequestFormEvent.REQUEST_ID}", type="com.kgis.fm.business.event.RequestFormEvent")]
    [Event(name="{com.kgis.fm.common.event.CommonEntityEvent.REQUEST_ID}", type="com.kgis.fm.common.event.CommonEntityEvent")]
    public class DrawPointFeature extends AbstractDrawFeature {
        protected var entityTypeId:Number;
        protected var relationEntitys:ArrayCollection;
        protected var layerId:int = 0;
        protected var drawFeature:Feature;
        protected var dialog:EntityDialog;
        protected var rotation:String;
		private var activeLE:LegendEntry;
		
        public function DrawPointFeature(entity:* = null) {
            super(entity);
            ViewRegistry.instance.eventBus.addParticipant(this);
        }

        override public function draw():void {
            snapFeatures = new ArrayCollection();
            drawHandler.snapClickCallback = snapClickCallback;
            drawHandler.active = true;
            if (!map.hasEventListener(DrawEvent.DRAW_POINT_FEATURE_END)) {
                map.addEventListener(DrawEvent.DRAW_POINT_FEATURE_END, onDrawFeatureEnd);
            }
        }

        protected function snapClickCallback(features:ArrayCollection, snapPoint:PointGeometry):void {
			for each(var feature:Feature in features)
			{
				if (!snapFeatures.contains(feature)) {
					snapFeatures.addItem(feature);
				}
			}
        }

        protected function onDrawFeatureEnd(event:DrawEvent):void {
            event.stopImmediatePropagation();
			drawFeature = event.drawFeature;
			drawHandler.active = false;
			map.removeEventListener(DrawEvent.DRAW_POINT_FEATURE_END, onDrawFeatureEnd);
            if (null == drawFeature) { //代表直接escape退出
                return;
            }
			activeLE= MetaDataManager.getLegendEntryById( drawFeature.layer.id);
            rotation = (drawFeature.geoStyle as PointStyle).rotation;
            if (StringUtils.isNullorEmpty(rotation)) {
                //没有方向不需要做编辑模式的旋转
                drawFeatureBusinessHandler();
            }
            else {
                drawFeature.fieldsMap = new Object();
                drawFeature.fieldsMap[rotation] = null;
                drawFeature.selected = true;
                var edithandler:EditHandler = new EditHandler(map, drawFeature);
                edithandler.activateEditMode(EditHandler.ROTATE);
                edithandler.active = true;
                map.addEventListener(EditEvent.GEOMETRY_EDITEND, onRotateFeatureEnd);
            }
        }

        protected function onRotateFeatureEnd(e:EditEvent):void {
            drawFeatureBusinessHandler();
            map.removeEventListener(EditEvent.GEOMETRY_EDITEND, onRotateFeatureEnd);
        }

        protected function drawFeatureBusinessHandler():void {
            //新增设施要保存的关系数据
            relationEntitys = new ArrayCollection();
            var feature:Feature;
           
            layerId = drawFeature.layer.id;
            if (null == entity) {
                //新增enttiy不需要判断是否有geometry
                //获得feature的layer id，然后找到eneitytypeid
                entityTypeId = activeLE.leno;
                if (entityTypeId) {
                    dispatchEvent(new RequestFormEvent([entityTypeId], RequestFormEvent.TYPE_NEW_ENTITY));
                }
            }
            else {
                //已经有entity，需要去数据库查询一遍是否有geometry，如果有提示已经有geometry，
                dispatchEvent(new CommonEntityEvent([entity.entityTypeId, entity.id, map.logicalMapId], CommonEntityEvent.TYPE_FIND_GEOMETRYENTITY_BYID));

            }

        }

        [ResponseHandler("{com.kgis.fm.business.event.RequestFormEvent.RETURN_ID}")]
        public function onRequestFormEvent(event:CommandCompletionEvent):void {
			entity = event.result;
			if(!entity)
			{
				entity=new GeometryEntity();
			}
            dialog = new EntityDialog();
			dialog.formType = AttributeDialogTab.FORM_TYPE_EDIT;
            dialog.submitFun = submitFunCallBack;
            dialog.cancelBack = onCancelBtn;
            dialog.entityTypeId = entityTypeId;
			var sridtype:String=MetaDataManager.getGeneralParameterByName("MAINCOORDINATESSYSTEM");
			if(sridtype=="1")
			{
				AbstractGeometry(drawFeature.geometry).srid=4326;
			}
            entity.geometry = drawFeature.geometry;
			entity.fno=activeLE.fno;
			entity.cno=activeLE.cno;
            /**
             * logicMapId
             * */
            entity.detailId = map.logicalMapId;
            if (!StringUtils.isNullorEmpty(rotation)) {
                entity.angle = drawFeature.fieldsMap[rotation];
            }
            dialog.entity = entity;
			dialog.submitFun = submitFunCallBack;
			dialog.cancelBack = onCancelBtn;
            PopUpManager.addPopUp(dialog, this.map.root, true);
            PopUpManager.centerPopUp(dialog);
        }

        protected function onCancelBtn():void {
            map.getLayerById(layerId).redraw();
        }

        protected function submitFunCallBack():void {
            dispatchEvent(new CommonEntityEvent([entity, relationEntitys], CommonEntityEvent.TYPE_SAVE_GEOMETRYENTITY));
        }

        [ResponseHandler("{com.kgis.fm.common.event.CommonEntityEvent.RETURN_ID}")]
        public function onCommandEvent(event:CommandCompletionEvent):void {
			var request:CommonEntityEvent = event.request as CommonEntityEvent;
            switch (request.actionType) {
                case CommonEntityEvent.TYPE_SAVE_GEOMETRYENTITY:
                    //entity = event.result;
                    //map.getLayerById(layerId).redraw();
                    if (dialog) {
                        dialog.loadingState = Dialog.LOADED;
                        PopUpManager.removePopUp(dialog);
                    }
					
					//得到编辑的属性
					var extAttr:ExtensionAttributes=new ExtensionAttributes();
					extAttr["KGM_CID"]=1;
					extAttr["KGM_ID"]=1;
					extAttr["KGM_SNO"]=200;
					for each(var attr:Object in dialog.propertyValueList)
					{
						extAttr[attr.field]=attr.value;
					}		
					entity.attributes=extAttr;
					//保存到数据库
					ServiceManager.getFmEntityManagementService().createGeometryEntity(entity as Entity,null,null);
					
                    //dispatchEvent(new AddGeometryEvent(entity, AddGeometryEvent.TYPE_ADD_GEOMETRY_END));
                    drawEnd();
                    break;
                case CommonEntityEvent.TYPE_FIND_GEOMETRYENTITY_BYID:
                    entity = event.result;
                    if (null != entity.geometry) {
                        ConfirmHelper.showConfirmDialog("", ResourceUtil.getString(StringConstants.FEATURE_HAS_GEOMETRY), function(evt:CloseEvent):void {
                                if (evt.detail == Alert.YES) {
                                    saveEntity();
                                }
                                else {
                                    //刷新图层
                                    map.refreshAllFeatureLayer();
                                    return;
                                }
                            });
                    }
                    else {
                        saveEntity();
                    }
                    break;
            }

        }

        override public function drawEnd():void {
            drawHandler.active = false;
            map.removeEventListener(DrawEvent.DRAW_POINT_FEATURE_END, onDrawFeatureEnd);
        }

        private function saveEntity():void {
            entity.geometry = drawFeature.geometry;
            /**
             * logicMapId
             * */
            entity.detailId = map.logicalMapId;
            if (!StringUtils.isNullorEmpty(rotation)) {
                entity.angle = drawFeature.fieldsMap[rotation];
            }
            dispatchEvent(new CommonEntityEvent([entity, relationEntitys], CommonEntityEvent.TYPE_SAVE_GEOMETRYENTITY));
        }
    }
}